﻿#region License
// Copyright (c) 2009 Shengmin Zhang
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Web;
using System.IO;
using System.IO.Compression;
using System.Text;
using System.Web.Caching;
using System.Collections.Specialized;
using System.Text.RegularExpressions;
using System.Collections.Generic;

using Apprender.Utilities;
using Apprender.Web.Configuration;
using Apprender.Web;


namespace Apprender.Web.Handlers
{
    public sealed class ClientResourceHandler : IHttpHandler
    {
        private HttpRequest _request;
        private HttpResponse _response;
        private HttpContext _context;

        #region IHttpHandler Members

        public bool IsReusable
        {
            get { return false; }
        }

        public void ProcessRequest(HttpContext context)
        {
            this._context = context;
            this._request = context.Request;
            this._response = context.Response;

            var querys = this._request.QueryString;
            var p = querys["p"];
            var type = this.GetContentType(querys["t"]);
            
            bool useGZip = UHttp.IsGZipSupported(this._request);            
            SetResponse(type, useGZip);

            string cacheKey = p + useGZip;
            byte[] output = _context.Cache[cacheKey] as byte[];            

            if(output == null) // no cache found
            {
                string[] paths = p.Split(',');
                int length = paths.Length;
                string[] newPaths = new string[length];

                int totalContentLength = 0;                

                bool disableCache = false;

                for (int i = 0; i < length; i++)
                {
                    bool ifExists;
                    int contentLength = 0;
                    string path = paths[i];
                    string newPath = this.GetPath(path, out ifExists, out contentLength);

                    if (ifExists)
                    {
                        newPaths[i] = newPath;
                        totalContentLength = totalContentLength + contentLength;
                    }
                    else
                    {
                        disableCache = true;
                    }

                    if (useGZip)
                    {
                        output = UCompression.GZipCompress(this.Read(newPaths, totalContentLength));
                    }
                    else
                    {
                        output = this.Read(newPaths, totalContentLength);
                    }

                    
                }

                if (!disableCache)
                {
                    _context.Cache.Add(cacheKey, output, new CacheDependency(newPaths), Cache.NoAbsoluteExpiration, TimeSpan.FromDays(7), CacheItemPriority.High, null);
                }
            }

            this._response.BinaryWrite(output);
            this._response.End();

        }

        #endregion



        private HttpResponseContentType GetContentType(string type)
        { 
            if (type[0] == 'j')
            {
                return HttpResponseContentType.JavaScript;
            }
            else
            {
                return HttpResponseContentType.Css;
            }                        
        }

        private void SetResponse(HttpResponseContentType type, bool useGZip)
        {
            _response.ContentType = (type == HttpResponseContentType.JavaScript) ? "application/x-javascript" : "text/css";
            _response.Charset = "utf-8";

            if (useGZip)
            {
                _response.AppendHeader("Content-Encoding", "gzip");
            }

#if !DEBUG
             _response.ExpiresAbsolute = DateTime.UtcNow.AddYears(1);            
            _response.Cache.SetCacheability(HttpCacheability.Public);
#endif

        }

        private string GetPath(string path, out bool ifExists, out int contentLength)
        {
            string newPath = _context.Server.MapPath(path);            
            string minPath = Path.ChangeExtension(newPath, ".min.js");

            if (File.Exists(minPath))
            {
                FileInfo file = new FileInfo(minPath);
                contentLength = (int)file.Length;

                ifExists = true;
                return minPath;
            }
            else if (File.Exists(newPath))
            {
                FileInfo file = new FileInfo(newPath);
                contentLength = (int)file.Length;

                ifExists = true;
                return newPath;
            }

            contentLength = 0;
            ifExists = false;
            return newPath;
        }

        private byte[] Read(string[] paths, int totalContentLength)
        {
           
            int start = 0;
            byte[] output = new byte[totalContentLength];           

            for (int i = 0; i < paths.Length; i++)
            {
                int contentLength = 0;
                string path = paths[i];
                
                if (path != null)
                {
                    FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read);
                    contentLength = (int)stream.Length;
                    try
                    {
                        stream.Read(output, start, contentLength);
                        
                    }
                    finally
                    {
                        stream.Close();
                    }
                    start = contentLength + start;
                }
                
            }
            return output;
        }
    }
}
